﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Baopx_API;

namespace A.Controller
{
    public class BackEndPageController
    {
        private static List<BackEndPage> _backEndPages = A.M.d.BackEndPages.ToList();

        private static void UpdateCache()
        {
            _backEndPages = A.M.d.BackEndPages.ToList();
        }

        public static List<BackEndPage> GetAllPageByMenuId(object menuId)
        {
            return _backEndPages.Where(i => i.MenuId == Convert.ToInt32(menuId) && i.IsActive).ToList();
        }

        public static List<BackEndPage> GetAllPage()
        {
            return _backEndPages.OrderByDescending(i => i.Id).ToList();
        }

        public static BackEndPage GetBackEndMenuPageCurrent()
        {
            return _backEndPages.SingleOrDefault(i => i.AbsolutePath == HttpContext.Current.Request.Url.AbsolutePath);
        }

        public static void InsertNewBackEndMenuPage()
        {
            BackEndPage backEndPage = GetBackEndMenuPageCurrent();
            if (backEndPage == null)
            {
                backEndPage = new BackEndPage();
                backEndPage.AbsolutePath = HttpContext.Current.Request.Url.AbsolutePath;
                backEndPage.IsActive = true;
                backEndPage.MenuId = 2;
                backEndPage.Name = Path.GetFileNameWithoutExtension(backEndPage.AbsolutePath);
                A.M.d.BackEndPages.InsertOnSubmit(backEndPage);
                A.M.d.SubmitChanges();
                UpdateCache();
            }
        }

        public static void Insert(BackEndPage backEndPageNew)
        {
            A.M.d.BackEndPages.InsertOnSubmit(backEndPageNew);
            A.M.d.SubmitChanges();
            UpdateCache();
        }

        public static void Update()
        {
            A.M.d.SubmitChanges();
            UpdateCache();
        }

        public static void Delete(BackEndPage backEndPageDelete)
        {
            A.M.d.BackEndPages.DeleteOnSubmit(backEndPageDelete);
            A.M.d.SubmitChanges();
            UpdateCache();
        }

        public static BackEndPage GetElementById(int id)
        {
            return _backEndPages.Single(i => i.Id == id);
        }
    }
}
